import jwt from 'jsonwebtoken';

const JWT_SECRET = 'your-secret-key'; // 生产环境请使用环境变量

export interface JwtPayload {
  userId: string;
  username: string;
  userIndex?: number;
  isAdmin: boolean;
}

export const generateToken = (payload: JwtPayload): string => {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: process.env.EXPIRESIN }); // 令牌有效期1小时
};

export const verifyToken = (token: string): JwtPayload | null => {
  try {
    return jwt.verify(token, JWT_SECRET) as JwtPayload;
  } catch (error) {
    return null;
  }
}